//
//  InfoAboutOrders.m
//  VivaModa
//
//  Created by Sergey on 4/3/13.
//  Copyright (c) 2013 private_busines. All rights reserved.
//

#import "InfoAboutOrders.h"
#import "infoAboutOrders_cell.h"
#import "infoAboutOrders_cell2.h"
#import "infoAboutOrders_cell3.h"

@interface InfoAboutOrders ()

@end

@implementation InfoAboutOrders
@synthesize connection;
@synthesize infoData;
@synthesize tableView;
@synthesize order_id;
@synthesize order_status;
@synthesize order_date;
@synthesize delivery_address;
@synthesize client_address;
@synthesize payment_method;
@synthesize tableView_;
@synthesize order_number;


NSArray *order_history;
NSArray *order_data;
NSArray *order_total_data;

NSString *text_order_id;
NSString *text_order_status;
NSString *text_order_date;
NSString *text_delivery_address;
NSString *text_client_address;
NSString *text_payment_method;







- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.backgroundColor = [Singleton sharedMySingleton].backgroundTableView;
    [self setNaviganionImg];
    [self setNavigationTitle];
    [self addCustomBackButton];

//////// http://moda.viva-viva.ru/mobile/order_info.php?order_id=403
}


-(void)viewWillAppear:(BOOL)animated{
    [self getData];
}



- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 3;
}




- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section==0) {
        return [order_history count];
    }else{
        if (section==1) {
            return [order_data count];
        }else{
            return [order_total_data count];
        }
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section==0) {
        static NSString *CellIdentifier1= @"infoAboutOrders_cell";
        infoAboutOrders_cell *cell_1 = nil;
        
        cell_1 = (infoAboutOrders_cell *) [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier1];
        if(!cell_1)
        {
            NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"infoAboutOrders_cell" owner:nil options:nil];
            for(id currentObject in topLevelObjects)
            {
                if([currentObject isKindOfClass:[infoAboutOrders_cell class]])
                {
                    cell_1 = (infoAboutOrders_cell *)currentObject;
                    break;
                }
            }
        }
        
        cell_1.orders_status_name.text = [[order_history objectAtIndex:indexPath.row] objectForKey:@"orders_status_name"];
        cell_1.date_added.text = [[order_history objectAtIndex:indexPath.row] objectForKey:@"date_added"];
        cell_1.comments.text = [[order_history objectAtIndex:indexPath.row] objectForKey:@"comments"];

        UIView *bg_sel = [[UIView alloc] initWithFrame:cell_1.bounds];
        bg_sel.backgroundColor = [UIColor clearColor];
        cell_1.selectedBackgroundView = bg_sel;
        
        cell_1.selectionStyle = UITableViewCellSelectionStyleNone;
        
        return cell_1;
    }else{
        if (indexPath.section==1) {
            static NSString *CellIdentifier2= @"infoAboutOrders_cell2";
            infoAboutOrders_cell2 *cell_2 = nil;
            
            cell_2 = (infoAboutOrders_cell2 *) [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier2];
            if(!cell_2)
            {
                NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"infoAboutOrders_cell2" owner:nil options:nil];
                for(id currentObject in topLevelObjects)
                {
                    if([currentObject isKindOfClass:[infoAboutOrders_cell2 class]])
                    {
                        cell_2 = (infoAboutOrders_cell2 *)currentObject;
                        break;
                    }
                }
            }
            
       
            cell_2.products_model.text = [[order_data objectAtIndex:indexPath.row] objectForKey:@"products_model"];
            cell_2.products_name.text = [[order_data objectAtIndex:indexPath.row] objectForKey:@"products_name"];
            cell_2.final_price.text = [[order_data objectAtIndex:indexPath.row] objectForKey:@"final_price"];
            cell_2.products_quantity.text = [[order_data objectAtIndex:indexPath.row] objectForKey:@"products_quantity"];
            cell_2.product_single_price.text = [NSString stringWithFormat:@"%@",[[order_data objectAtIndex:indexPath.row] objectForKey:@"product_single_price"]];
            
            UIView *bg_sel = [[UIView alloc] initWithFrame:cell_2.bounds];
            bg_sel.backgroundColor = [UIColor clearColor];
            cell_2.selectedBackgroundView = bg_sel;
            
            cell_2.selectionStyle = UITableViewCellSelectionStyleNone;
            return cell_2;
        }else{
            static NSString *CellIdentifier3= @"infoAboutOrders_cell3";
            infoAboutOrders_cell3 *cell_3 = nil;
            
            cell_3 = (infoAboutOrders_cell3 *) [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier3];
            if(!cell_3)
            {
                NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"infoAboutOrders_cell3" owner:nil options:nil];
                for(id currentObject in topLevelObjects)
                {
                    if([currentObject isKindOfClass:[infoAboutOrders_cell3 class]])
                    {
                        cell_3 = (infoAboutOrders_cell3 *)currentObject;
                        break;
                    }
                }
            }
            
            cell_3.title.text = [self stripTags:[[order_total_data objectAtIndex:indexPath.row] objectForKey:@"title"]];
            
            
            ;
            cell_3.value.text = [self stripTags:[[order_total_data objectAtIndex:indexPath.row] objectForKey:@"value"]];

            UIView *bg_sel = [[UIView alloc] initWithFrame:cell_3.bounds];
            bg_sel.backgroundColor = [UIColor clearColor];
            cell_3.selectedBackgroundView = bg_sel;
            
            cell_3.selectionStyle = UITableViewCellSelectionStyleNone;
            
            return cell_3;
        }
    }
}

- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    switch (indexPath.section) {
        case 0:{
            return 127;
            break;}
        case 1:{
            return 112;
            break;}
        case 2:{
            return 65;
            break;}
        default:
            break;
    }
    
    return 124;
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 45;
}


- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    // Create label with section title
    UILabel *label = [[UILabel alloc] init];
    label.frame = CGRectMake(0, 5, 315, 44);
    label.backgroundColor = [UIColor clearColor];
    label.textAlignment = UITextAlignmentCenter;
    
    [label setFont:[UIFont fontWithName:@"Arial-BoldMT" size:20.0]];
    [label setTextColor:[UIColor colorWithRed:29.0/255.0 green:38.0/255.0 blue:39.0/255.0 alpha:1]];
    
    
    
    switch (section) {
        case 0:{
            label.text = @"История заказа";
            break;}
        case 1:{
            label.text = @"Данные о заказе";
            break;}
        case 2:{
            label.text = @"Итог";
            break;}
        default:
            break;
    }
    
    
    
    
    
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 45)];
    [view addSubview:label];
    return view;
}




-(void)getData{
    
    
    
    NSURL* url = [NSURL URLWithString:[NSString stringWithFormat:@"http://moda.viva-viva.ru/mobile/order_info.php?order_id=%i",order_number]];
    NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:url];
    request.HTTPMethod = @"POST";
    connection = [NSURLConnection connectionWithRequest:request delegate:self];
    [self displayActivityView];
    if (connection) {
        self.infoData = [NSMutableData data];
    }

}


- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
    //[self removeActivityView];
    [self showNoInternetAlert];
}



- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [infoData appendData:data];
}


- (void)connectionDidFinishLoading:(NSURLConnection *)connection

{
    NSString *result = [[NSString alloc] initWithData:infoData encoding:NSUTF8StringEncoding];
    //NSLog(@"result = %@", result);
    
    
    [self parseJSON:infoData];
    
}


#pragma mark parse JSON result

-(void)parseJSON:(NSData*)data{
   
    
    NSError* error;
    
    NSDictionary* json = [NSJSONSerialization
                          
                          JSONObjectWithData:data
                          
                          options:kNilOptions
                          
                          error:&error];
    
    NSString* requestResultAutorization = [json objectForKey:@"success"];
    
    NSDictionary * dict_json = [json objectForKey:@"message"];
    
    //NSLog(@"json = %@",json);
    
    
    
    if ([requestResultAutorization integerValue]==1) {
        
        
            order_history = [dict_json objectForKey:@"order_history"];
            order_data = [dict_json objectForKey:@"order_data"];
            order_total_data = [dict_json objectForKey:@"order_total_data"];
            
            text_order_id = [dict_json objectForKey:@"order_id"];
            text_order_status =  [dict_json objectForKey:@"order_status"];
            text_order_date = [dict_json objectForKey:@"order_date"];
            text_delivery_address = [dict_json objectForKey:@"delivery_address"];
            text_client_address = [dict_json objectForKey:@"client_address"];
            text_payment_method = [dict_json objectForKey:@"payment_method"];
        
        
        
       
        
               
        
        
        
        [self reloadView];
    }else{
        UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"Уведомление" message:@"Ошибка синхронизации" delegate:nil cancelButtonTitle:@"Закрыть" otherButtonTitles:nil];
        [alert show];
        
    }
    
    
    
    [self removeActivityView];
    
    
    //[self performSelector:@selector(removeActivityView) withObject:nil afterDelay:0.7];
    
}




- (NSString *)stripTags:(NSString *)str
{
    NSMutableString *html = [NSMutableString stringWithCapacity:[str length]];
    
    NSScanner *scanner = [NSScanner scannerWithString:str];
    scanner.charactersToBeSkipped = NULL;
    NSString *tempText = nil;
    
    while (![scanner isAtEnd])
    {
        [scanner scanUpToString:@"<" intoString:&tempText];
        
        if (tempText != nil)
            [html appendString:tempText];
        
        [scanner scanUpToString:@">" intoString:NULL];
        
        if (![scanner isAtEnd])
            [scanner setScanLocation:[scanner scanLocation] + 1];
        
        tempText = nil;
    }
    
    return html;
}




-(void)reloadView{
    [self.tableView reloadData];
    
    order_id.text = text_order_id;
    order_date.text = text_order_date;
    order_status.text = text_order_status;
    delivery_address.text = text_delivery_address;
    client_address.text = text_client_address;
    payment_method.text = text_payment_method;
    [self.tableView_ reloadData];
    [self.tableView reloadData];
}

- (void)showNoInternetAlert
{
    BlockAlertView *alert = [BlockAlertView alertWithTitle:@"Ошибка Internet соединения" message:@"Для работы с магазином необходимо подключение к сети Internet. Пожалуйста, проверте подключение к сети и повторите попытку."];
    [alert setCancelButtonWithTitle:@"Закрыть" block:^{
        [UserDefaults setObject:@"NO" forKey:@"SuccsesUpdateCategories"];
        [self removeActivityView];
    }];
    //[alert setDestructiveButtonWithTitle:@"Повторить" block:nil];
    [alert addButtonWithTitle:@"Повторить " block:^{
        //[self displayActivityView];
        [self performSelector:@selector(parseCategories) withObject:nil afterDelay:1.0];
        //[self parseCategories];
    }];
    [alert show];
}


-(BOOL)InternetConnection{
    internetReach = [Reachability reachabilityForInternetConnection];
    NetworkStatus netStatus = [internetReach currentReachabilityStatus];
    if (netStatus == ReachableViaWiFi || netStatus == ReachableViaWWAN) {
        return YES;
    }else{
        return NO;
    }
    
}


-(void)setNaviganionImg{
    if ([self.navigationController.navigationBar respondsToSelector:@selector(setBackgroundImage:forBarMetrics:)] ) {
        UIImage *image = [UIImage imageNamed:@"navigation_bg"];
        [self.navigationController.navigationBar setBackgroundImage:image forBarMetrics:UIBarMetricsDefault];
        
    }
}

-(void)setNavigationTitle{
    UILabel *lblTitle = [[UILabel alloc] init];
    lblTitle.text = @" Детали заказа";
    lblTitle.backgroundColor = [UIColor clearColor];
    lblTitle.textColor = [UIColor colorWithRed:242.0/255.0 green:240.0/255.0 blue:234.0/255.0 alpha:1];
    
    lblTitle.font = [UIFont fontWithName:@"Arial" size:14.0];
    [lblTitle sizeToFit];
    
    self.navigationItem.titleView = lblTitle;
}



-(void)addCustomBackButton{
    UIButton *backButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 65, 29)];
    //[backButton setImage:[[UIImage imageNamed:@"img_back_btn.png"] resizableImageWithCapInsets:UIEdgeInsetsMake(10, 10, 10, 10) ] forState:UIControlStateNormal];
    
    [backButton setBackgroundImage:[[UIImage imageNamed:@"img_back_btn.png"] resizableImageWithCapInsets:UIEdgeInsetsMake(8, 20, 20, 20) ] forState:UIControlStateNormal];
    
    [backButton setTitle:@" Назад" forState:UIControlStateNormal];
    [backButton.titleLabel setFont:[UIFont fontWithName:@"Arial-BoldMT" size:12]];
    
    [backButton setShowsTouchWhenHighlighted:NO];
    [backButton addTarget:self action:@selector(popViewControllerWithAnimation) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *barBackItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    self.navigationItem.hidesBackButton = TRUE;
    self.navigationItem.leftBarButtonItem = barBackItem;
}

-(void)popViewControllerWithAnimation{
    [self.navigationController popViewControllerAnimated:YES];
}


#pragma mark Dejal activity

- (void)displayActivityView
{
    //[self removeActivityView];
    
    if ([DejalActivityView isActive]) {
        return;
    }
    
    UIView *viewToUse = self.tabBarController.tabBar.superview;
    [DejalBezelActivityView activityViewForView:viewToUse];
    [DejalActivityView currentActivityView].showNetworkActivityIndicator = YES;
    [DejalActivityView currentActivityView].activityLabel.text = @"Синхронизация";
    //[self performSelector:@selector(removeActivityView) withObject:nil afterDelay:3.0];
}

- (void)removeActivityView;
{
    [DejalBezelActivityView removeViewAnimated:YES];
    [[self class] cancelPreviousPerformRequestsWithTarget:self];
}

#pragma mark





@end
